package annotion.example.hss_fst.baselib.fragments;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import org.xutils.DbManager;
import org.xutils.db.DbManagerImpl;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;

import annotion.example.hss_fst.baselib.R;
import annotion.example.hss_fst.baselib.bean.Child;
import annotion.example.hss_fst.baselib.bean.User;

/**
 * @author 黄赛赛
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}()
 * @date 2016/6/5 13:26
 */
public class Dbfragment extends Fragment{
    DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
            .setDbName("test.db")
            // 不设置dbDir时, 默认存储在app的私有目录.
            .setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
            .setDbVersion(2)
            .setDbOpenListener(new DbManager.DbOpenListener() {
                @Override
                public void onDbOpened(DbManager db) {
                    // 开启WAL, 对写入加速提升巨大
                    db.getDatabase().enableWriteAheadLogging();
                }
            })
            .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                @Override
                public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                    // TODO: ...
                    // db.addColumn(...);
                    // db.dropTable(...);
                    // ...
                    // or
                    // db.dropDb();
                }
            });
    DbManager dbManager;
    View root_view;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        root_view =  inflater.inflate(R.layout.fragment_db,
                container, false);
        return  root_view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        dbManager =x.getDb(daoConfig);

        User user= new User();
        user.name = "lisi";
        user.age = 222;
//        Child child = new Child();
//        child.setName("zhang san ");
//        child.setText(" hello ");
        try {

            dbManager.save(user);
        } catch (DbException e) {
            e.printStackTrace();
        }
        TextView tv_result = (TextView) root_view.findViewById(R.id.tv_result);
        try {
            User  user1 =  dbManager.selector(User.class).findFirst();
            tv_result.setText(user1.toString());
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
}
